package service

import (
	"errors"
	"strconv"

	"sieve_admin_server_userpass/pkg/json"
)

type Config struct {
	val string
	err error
}

func (c *Config) String() (string, error) {
	if c.err != nil {
		return "", c.err
	}
	return c.val, nil
}

func (c *Config) Strings() ([]string, error) {
	if c.err != nil {
		return nil, c.err
	}
	list := []string{}
	err := json.Unmarshal([]byte(c.val), &list)
	return list, err
}

func (c *Config) Int() (int, error) {
	if c.err != nil {
		return 0, c.err
	}
	return strconv.Atoi(c.val)
}

func (c *Config) Ints() ([]int, error) {
	if c.err != nil {
		return nil, c.err
	}
	list := []int{}
	err := json.Unmarshal([]byte(c.val), &list)
	return list, err
}

func (c *Config) Map() (map[string]interface{}, error) {
	if c.err != nil {
		return nil, c.err
	}
	m := map[string]interface{}{}
	err := json.Unmarshal([]byte(c.val), &m)
	return m, err
}

func GetConfig(key string) *Config {
	ret := ""
	err := ReqSvc("config", "GetConfig", map[string]string{"Key": key}, &ret)
	return &Config{val: ret, err: err}
}

func SetConfig(key string, val interface{}) error {
	ret := ""
	if err := ReqSvc("config", "SetConfig", map[string]interface{}{
		"Key": key,
		"Val": val,
	}, &ret); err != nil {
		return err
	}
	if ret != "OK" {
		return errors.New("failed")
	}
	return nil
}

func GetConfigs(keys []string) (map[string]string, error) {
	ret := map[string]string{}
	err := ReqSvc("config", "GetConfigs", map[string]any{"Keys": keys}, &ret)
	return ret, err
}

func ReloadConfig() error {
	ret := ""
	if err := ReqSvc("config", "ReloadConfig", map[string]string{}, &ret); err != nil {
		return err
	}
	if ret != "OK" {
		return errors.New("failed")
	}
	return nil
}
